package com.content.scaffold.common.client.base;

import cn.hutool.json.JSONUtil;
import com.notarycloud.client.NotaryCloudSimpleResponse;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.List;


/**
 * @author xiaojl
 */
@Data
@Slf4j
public class ExternalBaseResponse<T> {

    private int code;

    private String message;

    private boolean isOk;

    private T data;


    private static <T> ExternalBaseResponse<T> success(Class<T> zClass, NotaryCloudSimpleResponse response) {
        T data = response.getDataAs(zClass);
        log.info(" 外呼 requestId : {}  返回 json ：{} ", response.getRequestId(), JSONUtil.toJsonStr(data));
        ExternalBaseResponse<T> result = new ExternalBaseResponse<>();
        result.setCode(response.getCode());
        result.setData(data);
        result.setOk(Boolean.TRUE);
        result.setMessage(response.getMessage());
        return result;
    }

    private static <T> ExternalBaseResponse<List<T>> successList(Class<T> zClass, NotaryCloudSimpleResponse response) {
        List<T> array = response.getDataAsArray(zClass);
        log.info(" 外呼 requestId : {}  返回 json ：{} ", response.getRequestId(), JSONUtil.toJsonStr(array));
        ExternalBaseResponse<List<T>> result = new ExternalBaseResponse<>();
        result.setCode(response.getCode());
        result.setData(array);
        result.setOk(Boolean.TRUE);
        result.setMessage(response.getMessage());
        return result;
    }

    private static <T> ExternalBaseResponse<T> fail(NotaryCloudSimpleResponse response) {
        ExternalBaseResponse<T> result = new ExternalBaseResponse<>();
        result.setCode(response.getCode());
        result.setOk(Boolean.FALSE);
        result.setMessage(response.getMessage());
        return result;
    }

    public static <T> ExternalBaseResponse<T> error(Exception e) {
        ExternalBaseResponse<T> result = new ExternalBaseResponse<>();
        result.setCode(-1);
        result.setOk(Boolean.FALSE);
        result.setMessage(e.getMessage());
        return result;
    }


    public static <T> ExternalBaseResponse<T> response(Class<T> zClass, NotaryCloudSimpleResponse response) {
        if (response.isOK()) {
            return success(zClass, response);
        }
        return fail(response);
    }


    public static <T> ExternalBaseResponse<List<T>> responseList(Class<T> zClass, NotaryCloudSimpleResponse response) {
        if (response.isOK()) {
            return successList(zClass, response);
        }
        return fail(response);
    }

}
